package com.jinzecloud.reportapproval.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.jinzecloud.reportapproval.bean.KeyInstrumentDetail;
import com.jinzecloud.reportapproval.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jinzecloud.reportapproval.mapper.ProductVerificaRecordMapper;
import com.jinzecloud.reportapproval.bean.ProductVerificaRecord;
import com.jinzecloud.reportapproval.service.ProductVerificaRecordService;

import javax.servlet.http.HttpServletRequest;


@Service("productVerificaRecordService")
public class ProductVerificaRecordServiceImpl extends ServiceImpl<ProductVerificaRecordMapper, ProductVerificaRecord> implements ProductVerificaRecordService {
    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private HttpServletRequest request;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductVerificaRecord> page = this.page(
                new Query<ProductVerificaRecord>().getPage(params),
                new QueryWrapper<ProductVerificaRecord>().like("test_location",params.get("key"))
        );

        return new PageUtils(page);
    }

    @Override
    public String createPdf(Integer id) {
        ProductVerificaRecord productVerificaRecord=getById(id);
        // 创建查询条件
        QueryWrapper<ProductVerificaRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("prototype_num", productVerificaRecord.getPrototypeNum());

        // 执行查询
        List<ProductVerificaRecord> dataList = list(queryWrapper);
        productVerificaRecord.setDataList(JSONUtil.parseArray(dataList));
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();

        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(productVerificaRecord));
        //word
        File tempFile = WordUtil.getWordFile("template/productverificare.docx", data, Configure.builder().bind("dataList", policy));

        if (tempFile == null) return null;
        String fileName = "生产查定记录表";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + productVerificaRecord.getProjectNum() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + productVerificaRecord.getProjectNum() +fileName;
        FileUtil.copyFile(tempFile, new File(filePath + ".docx"), StandardCopyOption.REPLACE_EXISTING);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));

        update(new LambdaUpdateWrapper<ProductVerificaRecord>().set(ProductVerificaRecord::getWordPath, savePath + ".docx").set(ProductVerificaRecord::getPdfPath, savePath + ".pdf").eq(ProductVerificaRecord::getId, id));
        return RequestUtils.getBasePath(request) + "upload/temp/" + productVerificaRecord.getProjectNum() + fileName + ".pdf";
    }

    @Override
    public JSONObject productVerificaRecordJson(String projectUuid) {
        // 创建查询条件
        QueryWrapper<ProductVerificaRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("prototype_num", projectUuid);

        // 执行查询
        List<ProductVerificaRecord> dataList = list(queryWrapper);

        if (dataList.size() <= 0) return null;

        ProductVerificaRecord productVerificaRecord = dataList.get(0);
        // 判断列表的大小是否小于 16
        if (dataList.size() < 16) {
            // 计算需要添加多少个元素
            int itemsToAdd = 16 - dataList.size();

            // 循环添加空的或默认的 KeyInstrumentDetail 对象
            for (int i = 0; i < itemsToAdd; i++) {
                ProductVerificaRecord emptyDetail = new ProductVerificaRecord();
                emptyDetail.setId((long) i);
                emptyDetail.setRecordDate("");
                emptyDetail.setStartDate("");
                emptyDetail.setEndDate("");
                emptyDetail.setContent("");
                emptyDetail.setTimeUsed("");
                emptyDetail.setHm2("");
                emptyDetail.setRemark("");
                // 如果需要，可以给 emptyDetail 设置默认值
                dataList.add(emptyDetail);
            }
        }
        JSONArray jsonArray = new JSONArray();
        JSONArray objects = JSONUtil.parseArray(dataList);
        System.out.println("dataList:" + dataList.toString());
        productVerificaRecord.setDataList(objects);
        System.out.println("productVerificaRecord:" + JSONObject.toJSONString(productVerificaRecord));
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(productVerificaRecord));
        return data;
    }

}
